<?php
declare (strict_types = 1);

namespace app\admin\controller;

class Admin extends BaseController
{
    public function getInfo()
    {
        $userInfo = $this->getUserInfo();
        success([
            'adminrole_id' => $userInfo['adminrole_id'],
            'adminrole_name' => '',
            'username' => $userInfo['username'],
            'areacode' => $userInfo['areacode'],
            'mobile' => $userInfo['mobile'],
            'email' => $userInfo['email'],
            'nickname' => $userInfo['nickname'],
            'avatar' => $userInfo['avatar'],
            'lastlogintime' => $userInfo['lastlogintime'],
            'lastloginip' => $userInfo['lastloginip'],
            'lastloginlocation' => $userInfo['lastloginlocation'],
        ]);
    }

    public function modifyPassword()
    {
        $data = $this->request->post();
        $this->validate($data, [
            "old_password" => "require",
            "new_password" => "require|password",
        ]);

        $userId = $this->getUserId();
        $userInfo = $this->db->name('admin_login')->field('password')->getInfo($userId);
        if (!password_verify($data['old_password'], $userInfo['password'])) {
            failure(104);
        }

        $saveData = [
            'password' => password_hash($data['new_password'], PASSWORD_DEFAULT),
        ];
        $this->db->name('admin_login')->saveInfo($saveData, $userId);
        success();
    }

    public function saveInfo()
    {
        $data = $this->request->post(['avatar', 'nickname', 'mobile', 'email']);
        $this->validate($data, [
            "avatar" => "max:255",
            "nickname" => "max:20|chsDash",
            "mobile" => "max:20|mobile",
            "email" => "max:20|email",
        ]);
        $userInfo = $this->getUserInfo();
        $this->db->name('admin_login')->saveInfo($data, $userInfo['id']);
        $userInfo = array_merge($userInfo, $data);
        $redis = redis_handle();
        $redis->set($this->getSessionKey(), json_encode($userInfo));
        $redis->close();
        success($data);
    }

    public function msgServer()
    {
        $info = [
            'uid' => $this->getUserId(),
        ];
        $token = sign_data($info, '', false);
        $cacheId = "cache_adminmessage_auth_{$token}";
        cache($cacheId, $info, 300);
        success([
            'protocol' => empty(config('app.server_adminmessage.enable_ssl')) ? 'ws' : 'wss',
            'host' => site_url(null),
            'port' => config('app.server_adminmessage.port'),
            'token' => $token,
        ]);
    }

    public function msgPush()
    {
        $msgData = [
            'info' => "push info to ws client",
        ];
        $clientInfo = [
            'uid' => $this->getUserId(),
        ];
        $result = push_message('server_adminmessage', 'apiPush', $msgData, $clientInfo);
        if (!$result) {
            failure();
        }
        success();
    }
}
